package cn.exrick.xboot.modules.assessment.controller;


import cn.exrick.xboot.base.XbootBaseController;
import cn.exrick.xboot.common.utils.CustomPage;
import cn.exrick.xboot.common.utils.CustomPageUtil;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.modules.assessment.entity.HkAssessmentIndex;
import cn.exrick.xboot.modules.assessment.entity.HkFormRelationShip;
import cn.exrick.xboot.modules.assessment.service.HkAssessmentIndexService;
import cn.exrick.xboot.modules.assessment.service.HkFormRelationShipService;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentIndexVo;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentInfoVo;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.beetl.ext.fn.ParseInt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
import static org.apache.poi.ss.usermodel.CellType.STRING;

/**
 * @author yck
 */
@Slf4j
@RestController
@Api(description = "考核指标管理接口")
@RequestMapping("/xboot/hkAssessmentIndex")
@Transactional
public class HkAssessmentIndexController extends XbootBaseController<HkAssessmentIndex, String> {

    @Autowired
    private HkAssessmentIndexService hkAssessmentIndexService;
    @Autowired
    private HkFormRelationShipService hkFormRelationShipService;

    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public HkAssessmentIndexService getService() {
        return hkAssessmentIndexService;
    }



    @RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public Result<CustomPage> getByCondition(HkAssessmentIndex hkAssessmentIndex,
                                                            SearchVo searchVo,
                                                            PageVo pageVo){
        pageVo.setOrder("createTime");
        pageVo.setSort("desc");
        Pageable pageable = PageRequest.of(pageVo.getPageNumber()-1, pageVo.getPageSize(), Sort.Direction.DESC,"createTime");
        Page<HkAssessmentIndex> page = hkAssessmentIndexService.findByCondition(hkAssessmentIndex, searchVo, pageable);
        for(HkAssessmentIndex assessmentIndex: page.getContent()){
            if(StrUtil.isNotBlank(assessmentIndex.getIndexScore())){
                if (assessmentIndex.getIndexType() == 2){
                    String replace = assessmentIndex.getIndexScore().replace(",", "~");
                    entityManager.clear();
                    assessmentIndex.setIndexScore(replace);
                }
                /*if (assessmentIndex.getIndexType() == 4){
                    String replace = assessmentIndex.getIndexScore().replace("-", "");
                    assessmentIndex.setIndexScore(replace);
                }*/

            }
        }
        CustomPage customPage = CustomPageUtil.getCustomPage(page);
        return new ResultUtil<CustomPage>().setData(customPage);
    }
    @RequestMapping(value = "/getHkAssessmentIndexList", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public Result getHkAssessmentIndexList(){
        List<HkAssessmentIndex> all = hkAssessmentIndexService.getAll();
        for(int i=0;i<all.size();i++){

        }
        return new ResultUtil().setData(all);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveHkAssessmentIndex")
    @ApiOperation(value = "新增指标项")
    public Result<Object> saveHkAssessmentIndex(HkAssessmentIndex hkAssessmentIndex) {
        return hkAssessmentIndexService.saveHkAssessmentIndex(hkAssessmentIndex);
    }

    @RequestMapping(value = "/updateIndex",method = RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value = "更新指标项数据")
    public Result updateIndex(HkAssessmentIndex hkAssessmentIndex){
        return  hkAssessmentIndexService.updateHkAssessmentIndex(hkAssessmentIndex);
    }

    @RequestMapping(value = "/getHkAssessmentIndexDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取指标项详情")
    public Result getHkAssessmentIndexDetail(String id){
        HkAssessmentIndex assessmentIndex = hkAssessmentIndexService.get(id);
        return new ResultUtil().setData(assessmentIndex);
    }

    @RequestMapping(value = "/delHkAssessmentIndex/{ids}", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    @ApiOperation(value = "通过id删除")
    public Result delHkAssessmentIndex(@PathVariable String[] ids) {

        for (int i = 0; i < ids.length; i++) {
            List<HkFormRelationShip> byItemId = hkFormRelationShipService.findByItemId(ids[i]);

            if (byItemId.size() > 0){
                HkAssessmentIndex byIndexName = hkAssessmentIndexService.get(ids[i]);
                return ResultUtil.error("请取消关联：(" + byIndexName.getIndexName() + ")与此指标相关的表单后再删除");
            }

            hkAssessmentIndexService.delete(ids[i]);
        }
        return ResultUtil.success("删除成功");
    }

    @PostMapping("/batchAddIndex")
    @ApiOperation(value = "指标项批量导入")
    public Result<Object> upload(MultipartFile file, HttpServletRequest request) throws Exception {
        InputStream inputStream = file.getInputStream();

        XSSFWorkbook wookbook = new XSSFWorkbook(inputStream);

        XSSFSheet sheet = wookbook.getSheet("Sheet1");

        //获取到Excel文件中的所有行数

        int rows = sheet.getPhysicalNumberOfRows();
        //遍历行

        List<HkAssessmentIndexVo> list = new ArrayList<HkAssessmentIndexVo>();

        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格

            XSSFRow row = sheet.getRow(i);

            // 行不为空
            if (row != null) {
                HkAssessmentIndexVo hkAssessmentIndexVo = new HkAssessmentIndexVo();

                //获取到Excel文件中的所有的列

                int cells = row.getPhysicalNumberOfCells();

                //指标项名称

                XSSFCell name =row.getCell(0);

                String indexName = getValue(name);

                if (StringUtils.isBlank(indexName)){
                    break;
                }
                //指标项描述

                XSSFCell Describe =row.getCell(1);

                String indexDescribe = getValue(Describe);

                //分数

                XSSFCell Score =row.getCell(2);

                String indexScore = getValue(Score);

                //指标类型
                XSSFCell type = row.getCell(3);

                String value = getValue(type);

                //指标分类id
                XSSFCell classifyId =row.getCell(4);

                String indexClassifyId = getValue(classifyId);

                //指标分类名称
                XSSFCell classifyName =row.getCell(5);

                String indexClassifyName = getValue(classifyName);

                //岗位id
                XSSFCell postId =row.getCell(6);

                String hontPostId = getValue(postId);

                //岗位名称
                XSSFCell postName =row.getCell(7);

                String hontPostName = getValue(postName);

                hkAssessmentIndexVo.setIndexName(indexName);
                hkAssessmentIndexVo.setIndexDescribe(indexDescribe);
                hkAssessmentIndexVo.setIndexScore(indexScore);
                hkAssessmentIndexVo.setIndexType(Integer.parseInt(value));
                hkAssessmentIndexVo.setHontPostId(hontPostId);
                hkAssessmentIndexVo.setHontPostName(hontPostName);
                hkAssessmentIndexVo.setIndexClassifyId(indexClassifyId);
                hkAssessmentIndexVo.setIndexClassifyName(indexClassifyName);

                list.add(hkAssessmentIndexVo);

            }

        }

        System.out.println("list = "+ JSON.toJSONString(list));
        StringBuffer msgString = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            log.info("指标名称：{}",list.get(i).getIndexName());
            HkAssessmentIndex byIndexName = hkAssessmentIndexService.findByIndexName(list.get(i).getIndexName());
            if (byIndexName != null){
                msgString.append(byIndexName.getIndexName());

            }
        }
        if (msgString.length() > 0 ){
            return ResultUtil.error(msgString.toString() + "以上指标名称已存在，请检查上传信息");
        }

        hkAssessmentIndexService.batchInsert(list);
//        for (int i = 0; i < list.size(); i++){
//            HkAssessmentIndex assessmentIndex = new HkAssessmentIndex();
//            assessmentIndex.setIndexName(list.get(i).get("indexName"));
//            assessmentIndex.setIndexDescribe(list.get(i).get("indexDescribe"));
//            assessmentIndex.setIndexScore(list.get(i).get("indexScore"));
//            hkAssessmentIndexService.save(assessmentIndex);
//        }
        return ResultUtil.success("上传成功");
    }

    private String getValue(XSSFCell xSSFCell){
        if(null == xSSFCell){
            return "";

        }

        if (xSSFCell.getCellType() == NUMERIC) {

            // 返回数值类型的值
            xSSFCell.setCellType(STRING);

            return String.valueOf(xSSFCell.getStringCellValue());

        } else {

            // 返回字符串类型的值

            return String.valueOf(xSSFCell.getStringCellValue());

        }

    }

    @RequestMapping(value = "/byFormEntityIdAndIndexType", method = RequestMethod.GET)
    @ApiOperation(value = "根据表单和指标类型查询指标项")
    public Result getHkAssessmentIndexListByFormEntityIdAndIndexId(String formEntityId,Integer indexId){
        List<HkAssessmentInfoVo> byFormEntityIdAndIndexType = hkAssessmentIndexService.findByFormEntityIdAndIndexType(formEntityId, indexId);
        return new ResultUtil().setData(byFormEntityIdAndIndexType);
    }

}
